/**
 * 封装了一些网络请求方法，方便通过 Promise 的形式请求接口
 */
 import $fetch from '@system.fetch'
 import $utils from './utils'
 const TIMEOUT = 8000
 
 Promise.prototype.finally = function (callback) {
   const P = this.constructor
   return this.then(
     value => P.resolve(callback()).then(() => value),
     reason =>
       P.resolve(callback()).then(() => {
         throw reason
       })
   )
 }
 
 /**
  * 调用快应用 fetch 接口做网络请求
  * @param params
  */
 function fetchPromise(params, page_name) {
   console.log('请求信息', JSON.stringify(params));
   console.log('请求信息page_name==>', page_name);
   let urlPrex = params.url.split('?')[0]
   if (!urlPrex) {
     urlPrex = params.url
   }
   console.log('请求接口前缀', urlPrex);
   return new Promise((resolve, reject) => {
     $utils.getStorage('token').then(res => {
       let curTimestamp = new Date().getTime()
       $fetch
         .fetch({
           url: params.url,
           method: params.method,
           data: params && params.data && params.data.complainSure ? params.data : JSON.stringify(params.data),
           header: { "authorization": res }
         })
         .then(response => {
           if (new Date().getTime() - curTimestamp > 1000) { //相应超过1000ms
             try {
              COMMON_REPORT_UTILS.error_log_report(`${urlPrex}`, `响应超过1000ms上报`, '接口请求', `响应超时`)
             } catch (e) {
 
             }
           }
           if (response.data.code < 500) {//code码 小于500
             console.log("🐛 response:", JSON.parse(response.data.data))
             let data = JSON.parse(response.data.data)
             if (data.tokenCode === 201) {
               $utils.setStorage('token', data.refreshToken)
             }
             if (data.code == 404) {
               try {
                 let _err = JSON.stringify(response.data)
                 COMMON_REPORT_UTILS.error_log_report(`${urlPrex}`, `${_err.substring(0, 1024).trim()}`, '接口请求', `找不到接口`)
               } catch (e) {
 
               }
 
             }
             resolve(data)
           } else { //code码 大于500
             try {
               let _err = JSON.stringify(response.data)
               COMMON_REPORT_UTILS.error_log_report(`${urlPrex}`, `${_err.substring(0, 1024).trim()}`, '接口请求', `内部错误`)
             } catch (e) {
 
             }
             reject(response.data)
           }
 
         })
         .catch((error, code) => {
           // let errorMsg = JSON.stringify(error)
           // console.log(`🐛 request fail, code = ${code}`)
           try {
             if (error && error.code && error.code == 2001) {
               return
             }
           } catch (error) {
 
           }
           try {
             console.log(JSON.stringify(error),'error===========================')
             console.log(code,'error===============code============')
             let _err = error.constructor == Object ? JSON.stringify(error) : `${error}`
             COMMON_REPORT_UTILS.error_log_report(`${urlPrex}`, `${_err.substring(0, 1024).trim()}`, '接口请求', `响应超时`)
           } catch (e) {
 
           }
 
           reject(error)
         })
     })
   })
 }
 
 /**
  * 处理网络请求，timeout 是网络请求超时之后返回，默认 8s 可自行修改
  * @param params
  */
 function requestHandle(params, page_name) {
 
   try {
     return Promise.race([
       fetchPromise(params, page_name),
     ])
   } catch (error) {
     console.log(error)
   }
 }
 
 export default {
   post: function (url, params, page_name) {
     return requestHandle({
       method: 'post',
       url: url,
       data: params
     }, page_name)
   },
   get: function (url, params, page_name) {
     return requestHandle({
       method: 'get',
       url: $utils.queryString(url, params)
     }, page_name)
   },
   put: function (url, params, page_name) {
     return requestHandle({
       method: 'put',
       url: url,
       data: params
     }, page_name)
   },
   delete: function (url, params, page_name) {
     return requestHandle({
       method: 'delete',
       url: url,
       data: params
     }, page_name)
   }
   // 如果，method 您需要更多类型，可自行添加更多方法；
 }
 